
package kalkon.outputModules;

import kalkon.OutputModule;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Output module implementation which stores files to local drives.
 *
 * Has no options. Just specify root dir and then getOutputStream().
 * 
 * @author tommz
 */
public class OutputModuleLocal implements OutputModule{

    private String rootDir;

    public void setOption(String option, String value) {
        // OK, no options to set
    }

    public void setRootDir(String dir) {
        rootDir = dir;
    }

    public OutputStream getOutputStream(String relativePath) {

        File f = new File(rootDir + File.separator + relativePath);

        if(!f.exists()){
            try {

                // make directories
                if(!f.getParentFile().exists()){
                    f.getParentFile().mkdirs();
                }

                f.createNewFile();
            } catch (IOException ex) {
               // ok, will be checked later
            }
        }

        if(!f.canWrite()){
            System.out.println("Cannot open file " + f.getPath() + " for writing.");
            return null;
        }

        OutputStream os;
        try {
            os = new FileOutputStream(f);
        } catch (FileNotFoundException ex) {
            System.out.println("Cannot open file " + f.getPath() + " for writing.");
            System.out.println(ex.toString());
            return null;
        }

        return os;

    }

}
